// pages/login/index.js
import {
  getTokenByCode,
  register
} from '../../api/user'
const app = getApp()
import {
  lockSysUser
} from '../../api/member'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chooseType: true
  },
  yinsi(){
    wx.navigateTo({
      url: '/pages/member/detail/detail?title=1&id=24354'
    })
  },


  tiaokuang(){
    wx.navigateTo({
      url: '/pages/member/detail/detail?title=2&id=24355'
    })
  },
  // changeType() {
  //   wx.showToast({
  //     duration: 2000,
  //     icon: "none",
  //     title: '请您先同意隐私政策以及服务协议'
  //   })
  //   return
  // },
  getUserInfo: function (e) {
    var _this = this;
    console.log(e)
    let mchId = app.globalData.mchId;
    if (app.APP_TYPE > 0) {
      mchId = app.ISV_ID
    }
    wx.login({
      success: wxres => {
        console.log(wxres)
        getTokenByCode({
          mchId: mchId,
          auth_code: wxres.code,
          uuid: app.globalData.uuid,
          pluginId: 'weixinMiniAuthPlugin'
        }).then(
          res => {
            console.log(res)
            if (res.type == 'success') {

              _this.callRegister(e)
            } else {
              wx.showToast({
                icon: "none",
                title: res.content
              })
            }
          }
        ).catch(error => {
          console.log(error)
        })
      }
    })


  },
  startLockSysUser() {
    lockSysUser({
      mchId: app.globalData.mchId,
      xuid: app.globalData.xuid,
      shopId: app.globalData.shopId
    }).then(res => {
      console.log("here is",res)
    })
  },
  callRegister: function (e) {
    var _this = this

    let mchId = app.globalData.mchId;
    if (app.APP_TYPE > 0) {
      mchId = app.ISV_ID
    }
    register({
      mchId: mchId,
      uuid: app.globalData.uuid,
      encryptData: e.detail.encryptedData,
      iv: e.detail.iv,
    }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          const {
            userInfo,
            token
          } = res.data
          app.globalData.token = token
          app.globalData.userInfo = userInfo
          _this.startLockSysUser();
          wx.switchTab({
            url: '/pages/index/index'
          })
          const eventChannel = _this.getOpenerEventChannel()
          eventChannel.emit('acceptDataFromOpenedPage', {
            cardType: _this.data.cardType
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.content
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  chooseClick() {
    this.data.chooseType = !this.data.chooseType
    this.setData({
      chooseType: this.data.chooseType
    })
  },
  phoneClick() {
    wx.navigateTo({
      url: '/pages/login/loginPhone',
    })
  }
})
